package com.pe1n.yangtaopai.service;

import android.app.Dialog;
import android.app.IntentService;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Environment;
import android.provider.Settings;
import android.support.v7.app.AlertDialog;
import android.util.Log;
import android.widget.Toast;

import com.pe1n.yangtaopai.bean.VersionBean;
import com.pe1n.yangtaopai.bean.VersionHelpBean;
import com.pe1n.yangtaopai.helper.InitRetrofitHelper;
import com.pe1n.yangtaopai.retrofitApi.RetrofitApi;
import com.pe1n.yangtaopai.utils.URLConstant;

import org.greenrobot.eventbus.EventBus;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;

import retrofit2.Retrofit;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

/**
 * Created by My on 2016/11/24.
 */

public class VersionService extends IntentService {
    private Context mContext;
    private int currentVersion;//当前的版本
    private RetrofitApi mRetrofitApi;
    private String string;
    private Notification notification;
    public VersionService() {
        super("VersionService");
    }

    @Override
    protected void onHandleIntent(Intent intent) {
        currentVersion = intent.getIntExtra("VERSION_CURRENT", 1);
        string=intent.getStringExtra("VERSION_URL");
        mContext = this;
        try {
            sendNotification();
        } catch (IOException e) {
            e.printStackTrace();
        }


    }

    private void sendNotification() throws IOException {
        NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        Notification.Builder builder1 = new Notification.Builder(this);
        builder1.setContentTitle("正在下载");
        builder1.setSmallIcon(android.R.mipmap.sym_def_app_icon);
        builder1.setContentText("下载中···");
        Notification notification = builder1.build();
        notification.icon = android.R.mipmap.sym_def_app_icon;
        notification.when = System.currentTimeMillis();
        notification.defaults = notification.DEFAULT_ALL;
        notificationManager.notify(0, notification);
        URL url = null;
        HttpURLConnection coon = null;
        FileOutputStream fs = null;
        File file = null;
        BufferedInputStream bufferedInputStream = null;
        try {
            url = new URL(string);
            coon = (HttpURLConnection) url.openConnection();
            int length = coon.getContentLength();
            coon.setConnectTimeout(5000);
            coon.setReadTimeout(5000);
            if (coon.getResponseCode() == HttpURLConnection.HTTP_OK) {
                InputStream is = coon.getInputStream();
                bufferedInputStream = new BufferedInputStream(is);
                byte[] bytes = new byte[1024*8];
                 file = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS) + File.separator + "vi.apk");
                fs = new FileOutputStream(file);
                int len = 0;
                int curr=0;
                while ((len = bufferedInputStream.read(bytes)) != -1) {
                    Log.e("tag", String.valueOf(len));
                    fs.write(bytes, 0, len);
                    fs.flush();
                    curr+=len;
                    Log.e("tag",String.valueOf(curr));
                    builder1.setProgress(length, curr, false);
                    builder1.setSmallIcon(android.R.mipmap.sym_def_app_icon);
                    builder1.setContentText("已下载 " + String.valueOf((curr* 100 / length)+1)+"%");
                    notification=builder1.build();
                    notification.flags=Notification.FLAG_AUTO_CANCEL;
                    notificationManager.notify(0,notification);
                }

                Intent intent=new Intent();
                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                intent.setAction(Intent.ACTION_VIEW);
                intent.setDataAndType(Uri.fromFile(file),"application/vnd.android.package-archive");
                PendingIntent pi=PendingIntent.getActivity(mContext,1,intent,PendingIntent.FLAG_UPDATE_CURRENT);
                builder1.setContentIntent(pi);
                Log.e("下载完成","dd");
                builder1.setSmallIcon(android.R.mipmap.sym_def_app_icon);
                builder1.setContentText("下载完成");
                notificationManager.notify(1,builder1.build());
            }

        } catch (MalformedURLException e) {
            e.printStackTrace();
        } finally {
            if (coon != null) {
                coon.disconnect();
            }
            if (bufferedInputStream != null) {
                bufferedInputStream.close();
            }
            if (fs != null) {
                fs.close();
            }
        }


    }
}
